package com.gis.util;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ErrorHandler extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// 处理 GET 方法请求的方法
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 异常对象
//		Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
		
		// 异常状态码
		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
		
		// 异常类型
		Object exceptionType = request.getAttribute("javax.servlet.error.exception_type");
		
		// 异常信息
		String message = (String) request.getAttribute("javax.servlet.error.message");
		
		// 产生异常的 Servlet
		String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
		if (servletName == null) {
			servletName = "Unknown";
		}
		
		// 产生异常的uri
		String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
		if (requestUri == null) {
			requestUri = "Unknown";
		}
		
		ExceptionObject exceptionObject = new ExceptionObject();
		exceptionObject.setExceptionType(exceptionType);
		exceptionObject.setServletName(servletName);
		exceptionObject.setRequestUri(requestUri);
		exceptionObject.setMessage(message);
		exceptionObject.setStatusCode(statusCode);
		
		// 设置响应内容类型
		response.setContentType("text/html;charset=UTF-8");

		if(statusCode == 404) {
			ResponseUtil.writeJson(response, RestResponse.fail(ResultCode.PAGE_NOT_FOUND, exceptionObject));
		}
		ResponseUtil.writeJson(response, RestResponse.fail(ResultCode.FAIL, exceptionObject));
	}

	// 处理 POST 方法请求的方法
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
class ExceptionObject {
	Throwable throwable;
	Integer statusCode;
	Object exceptionType;
	String servletName;
	String requestUri;
	String message;
	public Throwable getThrowable() {
		return throwable;
	}
	public void setThrowable(Throwable throwable) {
		this.throwable = throwable;
	}
	public Integer getStatusCode() {
		return statusCode;
	}
	public void setStatusCode(Integer statusCode) {
		this.statusCode = statusCode;
	}
	public Object getExceptionType() {
		return exceptionType;
	}
	public void setExceptionType(Object exceptionType) {
		this.exceptionType = exceptionType;
	}
	public String getServletName() {
		return servletName;
	}
	public void setServletName(String servletName) {
		this.servletName = servletName;
	}
	public String getRequestUri() {
		return requestUri;
	}
	public void setRequestUri(String requestUri) {
		this.requestUri = requestUri;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	
	
	
}